const path = require('path');
const bree = require('../lib/bree');

class Reminder {
  constructor() {
    this.jobNameRegex = /^reminder-userId:\d+-taskId:\d+$/;
    this.jobPath = path.join(bree.config.root, 'remind.js');
  }

  createReminderName(userId, taskId) {
    return `reminder-userId:${userId}-taskId:${taskId}`;
  }

  checkReminderName(name) {
    return this.jobNameRegex.test(name);
  }

  async addTaskReminder(userId, taskId, email, content, remindTime) {
    const jobName = this.createReminderName(userId, taskId);
    const exist = bree.config.jobs.find(job => {
      return (job.name === jobName);
    });
    if (exist) {
      await bree.remove(jobName);
    }
    await bree.add({
      name: jobName,
      path: this.jobPath,
      date: remindTime,
      worker: {
        workerData: {
          email,
          content,
          remindTime
        }
      }
    });
    await bree.start(jobName);
  }

  async removeTaskReminder(userId, taskId) {
    const jobName = this.createReminderName(userId, taskId);
    const exist = bree.config.jobs.find(job => {
      return (job.name === jobName);
    });
    if (exist) {
      await bree.remove(jobName);
    }
  }
}

module.exports = Reminder;